package com.demo.user.validation;


import org.apache.commons.beanutils.BeanUtils;

import javax.validation.Constraint;
import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import javax.validation.Payload;
import java.lang.annotation.Documented;
import java.lang.annotation.Repeatable;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
import java.lang.reflect.InvocationTargetException;

import static java.lang.annotation.ElementType.*;
import static java.lang.annotation.RetentionPolicy.RUNTIME;

/**
 * @author xiexiaohu
 */
@Target({TYPE, ANNOTATION_TYPE, FIELD})
@Retention(RUNTIME)
@Repeatable(NotNullIfAnotherFieldHasValue.List.class)
@Constraint(validatedBy = NotNullIfAnotherFieldHasValue.Validator.class)
@Documented
public @interface NotNullIfAnotherFieldHasValue {
    String fieldName();

    String fieldValue();

    String dependFieldName();

    String message() default "{javax.validation.constraints.NotNull.message}";

    Class<?>[] groups() default {};

    Class<? extends Payload>[] payload() default {};

    @Target({TYPE, ANNOTATION_TYPE})
    @Retention(RUNTIME)
    @Documented
    @interface List {
        NotNullIfAnotherFieldHasValue[] value();
    }

    class Validator
        implements ConstraintValidator<NotNullIfAnotherFieldHasValue, Object> {
        private String fieldName;
        private String expectedFieldValue;
        private String dependFieldName;

        @Override
        public void initialize(NotNullIfAnotherFieldHasValue constraintAnnotation) {
            fieldName          = constraintAnnotation.fieldName();
            expectedFieldValue = constraintAnnotation.fieldValue();
            dependFieldName    = constraintAnnotation.dependFieldName();
        }

        @Override
        public boolean isValid(Object value, ConstraintValidatorContext context) {
            if (value == null) {
                return true;
            }

            try {
                String fieldValue       = BeanUtils.getProperty(value, fieldName);
                String dependFieldValue = BeanUtils.getProperty(value, dependFieldName);

                if (expectedFieldValue.equals(fieldValue) && dependFieldValue == null) {
                    context.disableDefaultConstraintViolation();
                    context.buildConstraintViolationWithTemplate(context.getDefaultConstraintMessageTemplate())
                        .addPropertyNode(dependFieldName)
                        .addConstraintViolation();
                    return false;
                }

            } catch (NoSuchMethodException | InvocationTargetException | IllegalAccessException ex) {
                throw new RuntimeException(ex);
            }

            return true;
        }
    }
}
